package org.dialMsg.Contrllor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dialMsg.Pojo.DataSourceBatchDetail;
import org.dialMsg.Pojo.TCrmCallLog;
import org.dialMsg.Pojo.TDataSourceBatch;
import org.dialMsg.Pojo.TDialResult;
import org.dialMsg.ResultBean.ResponseBean;
import org.dialMsg.Server.ServerInt.DimSyncServer;
import org.dialMsg.Server.ServerInt.SeatDataSourceBatchService;
import org.dialMsg.Server.ServerInt.TCrmCallLogService;
import org.dialMsg.Server.ServerInt.TDataSourceBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author DPF
 */
@RestController
@RequestMapping("/dataSourceBatch")
public class TDataSourceBatchController {
    @Autowired
    private TDataSourceBatchService dataSourceBatchService;
    @Qualifier("seatDataSourceBatchServiceImpl")
    @Autowired
    private SeatDataSourceBatchService seatBatchService;
    @Qualifier("dimSyncServerImp")
    @Autowired
    private DimSyncServer dimDataBatchService;


    @PostMapping("/insert")
    public ResponseEntity<ResponseBean<Void>> insert(@RequestHeader HttpHeaders headers, @RequestBody TDataSourceBatch dataSourceBatch) {
        // 确保 Content-Type 是具体的 MIME 类型
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);

        try {
            dataSourceBatchService.insertBatchWithDetails(dataSourceBatch);
            return ResponseEntity.ok()
                    .headers(responseHeaders)
                    .body(ResponseBean.success(null));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500)
                    .headers(responseHeaders)
                    .body(ResponseBean.error(500, "Insert 话单 failed"));
        }
    }

    @GetMapping("/insertdim/{size}")
    public ResponseEntity<ResponseBean<Void>> insertdim(@RequestHeader HttpHeaders headers, @PathVariable Integer size) {
        // 确保 Content-Type 是具体的 MIME 类型
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        try {
            List<TDataSourceBatch> tDataSourceBatches = dataSourceBatchService.queryBySize(size);
            tDataSourceBatches.forEach(tDataSourceBatch -> {
                seatBatchService.insertSeatBatchSize(tDataSourceBatch.getId(),
                        tDataSourceBatch.getShowName(),
                        tDataSourceBatch.getTaskId(),
                        tDataSourceBatch.getCompanyUserId(),
                        tDataSourceBatch.getUploadUserId(),
                        tDataSourceBatch.getBusinessId(),
                        tDataSourceBatch.getDataBatchType(),
                        8,
                        tDataSourceBatch.getSourceUploadNum(),
                        tDataSourceBatch.getUploadNum(),
                        tDataSourceBatch.getSourceUploadNum(),
                        tDataSourceBatch.getComment(),
                        tDataSourceBatch.getStatus(),
                        tDataSourceBatch.getTimeCreate(),
                        tDataSourceBatch.getTimeModified()
                );
                dimDataBatchService.insertBatchSize(tDataSourceBatch.getId(),
                        tDataSourceBatch.getShowName(),
                        tDataSourceBatch.getBusinessId(),
                        tDataSourceBatch.getCompanyUserId(),
                        tDataSourceBatch.getUploadUserId(),
                        tDataSourceBatch.getUploadNum(),
                        tDataSourceBatch.getUploadDealTime());
            });
            return ResponseEntity.ok()
                    .headers(responseHeaders)
                    .body(ResponseBean.success(null));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500)
                    .headers(responseHeaders)
                    .body(ResponseBean.error(500, "Insert 批次 failed"));
        }
    }

    // 根据 ID 查询数据
    @GetMapping("/selectById/{id}")
    public ResponseBean<TDataSourceBatch> selectById(@PathVariable Integer id) {
        TDataSourceBatch result = dataSourceBatchService.selectById(id);
        if (result != null) {
            return ResponseBean.success(result);
        } else {
            return ResponseBean.error(404, "Data not found");
        }
    }

    // 查询所有数据
    @GetMapping("/selectAll")
    public ResponseBean<List<TDataSourceBatch>> selectAll() {
        List<TDataSourceBatch> result = dataSourceBatchService.selectAll();
        return ResponseBean.success(result);
    }

    // 更新数据
    @PutMapping("/update")
    public ResponseBean<Integer> update(@RequestBody TDataSourceBatch dataSourceBatch) {
        int result = dataSourceBatchService.update(dataSourceBatch);
        if (result > 0) {
            return ResponseBean.success(result);
        } else {
            return ResponseBean.error(500, "Update failed");
        }
    }

    // 根据 ID 删除数据
    @DeleteMapping("/deleteById/{id}")
    public ResponseBean<Integer> deleteById(@PathVariable Integer id) {
        int result = dataSourceBatchService.deleteById(id);
        if (result > 0) {
            return ResponseBean.success(result);
        } else {
            return ResponseBean.error(500, "Delete failed");
        }
    }

    @GetMapping("/bodyEmitter")
    public ResponseBodyEmitter handle() {
        // 创建一个ResponseBodyEmitter，-1代表不超时
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L);
        // 异步执行耗时操作
        CompletableFuture.runAsync(() -> {
            try {
                // 模拟耗时操作
                for (int i = 0; i < 10000; i++) {
                    System.out.println("bodyEmitter " + i);
                    // 发送数据
                    emitter.send("bodyEmitter " + i + " @ " + new Date() + "\n");
                    Thread.sleep(2000);
                }
                // 完成
                emitter.complete();
            } catch (Exception e) {
                // 发生异常时结束接口
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }

    private static final Map<String, SseEmitter> EMITTER_MAP = new ConcurrentHashMap<>();

    @GetMapping("/subSseEmitter/{userId}")
    public SseEmitter sseEmitter(@PathVariable String userId) {
        SseEmitter emitterTmp = new SseEmitter(-1L);
        EMITTER_MAP.put(userId, emitterTmp);
        CompletableFuture.runAsync(() -> {
            try {
                SseEmitter.SseEventBuilder event = SseEmitter.event()
                        .data("sseEmitter" + userId + " @ " + LocalTime.now())
                        .id(String.valueOf(userId))
                        .name("sseEmitter");
                emitterTmp.send(event);
            } catch (Exception ex) {
                emitterTmp.completeWithError(ex);
            }
        });
        return emitterTmp;
    }

    @GetMapping("/sendSseMsg/{userId}")
    public void sseEmitter(@PathVariable String userId, String msg) throws IOException {
        SseEmitter sseEmitter = EMITTER_MAP.get(userId);
        if (sseEmitter == null) {
            return;
        }
        try {
            sseEmitter.send(msg);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/streamingResponse")
    public ResponseEntity<StreamingResponseBody> handleRbe() {

        StreamingResponseBody stream = out -> {
            String message = "streamingResponse";
            for (int i = 0; i < 100; i++) {

                out.write(((message + i) + "\r\n\r\n").getBytes());
                out.write("\r\n".getBytes());
                //调用一次flush就会像前端写入一次数据
                out.flush();

            }

        };
        return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(stream);
    }

}